
package es.upm.dit.gsi.opactv.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class Connection {

    public Connection() {
        // NADA!
    }

    public String get(String pURL) {
        String response = "";
        try {
            URL url = new URL(pURL);
            URLConnection uc = url.openConnection();
            String charset = uc.getContentType();
            int index = charset.indexOf("charset=");
            InputStreamReader isr;
            if (index==-1) isr = new InputStreamReader(uc.getInputStream(), "ISO-8859-1");
            else isr = new InputStreamReader(uc.getInputStream(), charset.substring(index+8));
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line=br.readLine())!=null) {
                response += line;
            }
        } catch (Exception ex) {
            //System.err.println(ex);
        } finally {
            return response;
        }
    }

    public String post(String pURL, String params) {
        String response = "";
        try {
            URL url = new URL(pURL);
            URLConnection uc = url.openConnection();
            uc.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
            wr.write(params);
            wr.flush();
            String charset = uc.getContentType();
            int index = charset.indexOf("charset=");
            InputStreamReader isr;
            if (index==-1) isr = new InputStreamReader(uc.getInputStream(), "ISO-8859-1");
            else isr = new InputStreamReader(uc.getInputStream(), charset.substring(index+8));
            BufferedReader br = new BufferedReader(isr);
            String content;
            while ((content = br.readLine())!=null){
                response += content;
            }
            br.close();
            wr.close();
        } catch (Exception ex) {
            //System.err.println(ex);
        } finally {
            return response;
        }
    }

    public void getFile(String pURL, File file) {
        try {
            URL url = new URL(pURL);
            URLConnection connection = url.openConnection();
            InputStream stream = connection.getInputStream();
            BufferedInputStream in = new BufferedInputStream(stream);
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream out = new BufferedOutputStream(fos);
            int i;
            while ((i = in.read()) != -1) {
                out.write(i);
            }
            out.flush();
        } catch (Exception ex) {
            //System.err.println(ex);
        }
    }

}
